package com.cjy.drools.xls;


import com.cjy.drools.pojo.Person;
import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.utils.KieHelper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * 决策表 是规则文件的一种变形，是以xls、xlsx为扩展名的文件，是指通过Excel完成对规则的匹配
 *
 * @author cjy
 * @create 2020-04-01
 */
public class RulesTable {

    public static void main(String[] args) {
    }


    /**
     * excel 文件测试 xls文件不要在其他地方打开，保存为97-03的工作簿
     */
    @Test
    public void testisXls() {
        KieServices kss = KieServices.Factory.get();
        KieContainer kc = kss.getKieClasspathContainer();
        KieSession ks = kc.newKieSession("isXLS");

        int count = ks.fireAllRules();

        System.out.println("总得执行了" + count + "条规则");
        ks.dispose();
    }

    /**
     * 表格内容居中对齐
     */
    @Test
    public void testisXls2() {
        KieServices kss = KieServices.Factory.get();
        KieContainer kc = kss.getKieClasspathContainer();
        KieSession ks = kc.newKieSession("isxlsS");

        Person p = new Person();
        p.setName("李四");
        p.setAge(25);
        ks.insert(p);

        int count = ks.fireAllRules();
        System.out.println("总得执行了" + count + "条规则");
        ks.dispose();
    }


    /**
     * 通过生成的drl内容来检测决策表是否正确
     *
     * @throws FileNotFoundException
     */
    @Test
    public void verificationDT() throws FileNotFoundException {
        File file = new File("E:\\workspace_Scala\\rule-engine\\drool-engine\\src\\main\\resources\\rules\\tableXlsS.xls");
        InputStream in = new FileInputStream(file);

        SpreadsheetCompiler converter = new SpreadsheetCompiler();
        String drl = converter.compile(in, InputType.XLS);

        System.out.println(drl);
    }

    /**
     * 调用决策表的另一种方式：通过drool工具类kiehelper
     * 不需要kmodule.xml文件里编写
     */
    @Test
    public void testKieHelper() {
        Resource dis = ResourceFactory.newClassPathResource("rules/tableXlsS.xls");
        KieHelper helper = new KieHelper();

        helper.addResource(dis, ResourceType.DTABLE);

        KieSession kieSession = helper.build().newKieSession();

        Person p = new Person();
        p.setName("李四");
        p.setAge(25);
        kieSession.insert(p);

        int i = kieSession.fireAllRules();
        System.out.println("执行" + i + "次数");

    }


}
